<?php

function packer_pack($source)
{
	// join php code
	$source = preg_replace('#<\\?php\\s*\\?>#si', '', $source);
	$source = preg_replace('#\\?>\s*<\\?php#si', ' ', $source);
	$tokens = token_get_all($source);
	$out    = '';
	$tc  = count($tokens);
	$idx = 0;
	$whitespace = false;
	while($idx < $tc) {
		$token = $tokens[$idx];
		if (is_string($token)) {
			// simple 1-character token
			$out .= $token;
			$whitespace = false;
		} else {
			// token array
			list($id, $text) = $token;

			switch ($id) { 
			case T_COMMENT: 
			//case T_ML_COMMENT:  // we've defined this (PHP4 only)
			case T_DOC_COMMENT: // and this
				// no action on comments
			case T_WHITESPACE:  // and this
				if (!$whitespace) $out .= ' ';
				$whitespace = true;
				break;

			default:
				// anything else -> output "as is"
				$out .= $text;
				$whitespace = false;
				break;
			}
		}
		$idx++;
	}
	return $out;
}
